﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using BALayer;

namespace PGBT
{
    public partial class FormTraHang : Form
    {
        private GiaoDich dbGG = null;
        private HangHoa dbHH = null;
        private DataSet dsNCC = null;
        private BindingSource bs = null;

        public FormTraHang()
        {
            InitializeComponent();
        }

        private void FormTraHang_Load(object sender, EventArgs e)
        {
            dbGG = new GiaoDich();
            dbHH = new HangHoa();
            bs = new BindingSource();

            dsNCC = dbHH.NhaCungCapCoHangHetHan();

            cbNCC.DataSource = dsNCC.Tables[0];
            cbNCC.DisplayMember = "tenncc";
        }

        private void cbNCC_SelectedIndexChanged(object sender, EventArgs e)
        {
            txtTenNCC.Text = dsNCC.Tables[0].Rows[cbNCC.SelectedIndex].ItemArray[1].ToString();

            bs.DataSource = dbHH.DanhSachHangHetHan();
            bs.Filter = "id='" + dsNCC.Tables[0].Rows[cbNCC.SelectedIndex].ItemArray[0].ToString() + "'";
            dgvHangHoa.DataSource = bs;
        }

        private void btnTraHang_Click(object sender, EventArgs e)
        {
            string error = "";

            dbGG.BeginTransaction();

            int mancc = Convert.ToInt32(dsNCC.Tables[0].Rows[cbNCC.SelectedIndex].ItemArray[0].ToString());
            int madontrahang = -1;

            try
            {
                madontrahang = dbGG.TaoDonTraHang(ref error, mancc, DateTime.Now);
                if (madontrahang == -1)
                    throw new Exception(error);

                for (int i = 0; i < dgvHangHoa.Rows.Count - 1; i++)
                {
                    int manhaphang = Convert.ToInt32(dsNCC.Tables[0].Rows[cbNCC.SelectedIndex].ItemArray[1].ToString());
                    int mahang = Convert.ToInt32(dsNCC.Tables[0].Rows[cbNCC.SelectedIndex].ItemArray[4].ToString());
                    int soluong = Convert.ToInt32(dsNCC.Tables[0].Rows[cbNCC.SelectedIndex].ItemArray[6].ToString());

                    if (!dbGG.ThemHangVaoDonTraHang(ref error, madontrahang, manhaphang, mahang, soluong))
                        throw new Exception(error);
                }
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }
}
